#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "member.h"
#include "common.h"
#include "manager.h"

#define MEMBER_INFO_FILE "data/member_info.dat"
#define MEMBER_ID_BASE   100001


void print_member_info(const member_info* mi);


static unsigned int get_new_mid(void)
{
	member_info mi;
	unsigned int mid;

	FILE* fp = fopen(MEMBER_INFO_FILE, "rb");

	if(fp == NULL)
	{
		return MEMBER_ID_BASE;
	}

	fseek(fp, -sizeof(mi), SEEK_END);
	
	if(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		mid = mi.mid + 1;
	}
	else
	{
		mid = MEMBER_ID_BASE;
	}

	fclose(fp);

	return mid;
}


void member_reg(void)   //  注册
{
	member_info mi;

	printf("请按照如下提示输入会员信息。\n\n");
	printf("卡号：");
	scanf("%s", mi.card_num);
	printf("姓名：");
	scanf("%s", mi.name);
	printf("性别（1-女,2-男）：");
	scanf("%d", (int*)&mi.s);
	printf("手机号：");
	scanf("%s", mi.phone);
	printf("会员类型（1-次卡,2-月卡,3-年卡）：");
	scanf("%d", (int*)&mi.mt);

	if(mi.mt == cika)
	{
		printf("剩余次数：");
		scanf("%d", &mi.remain_cnt);
	}

	mi.reg_time = time(NULL);

	if(mi.mt == yueka)
		mi.expire_time = mi.reg_time + 30 * 24 * 60 * 60;
	else
		mi.expire_time = mi.reg_time + 365 * 24 * 60 * 60;

	mi.mid = get_new_mid();
	mi.delete_state = 0;

	FILE* fp = fopen(MEMBER_INFO_FILE, "ab");
	
	if(fp == NULL)
	{
		perror("会员注册失败");
		return;
	}

	fwrite(&mi, sizeof(mi), 1, fp);

	fclose(fp);

	printf("\n注册会员成功！\n");
	printf("即将返回主菜单！\n");
	sleep(3);
}


void member_show(void)
{
	member_info mi;
	char card_num[11];

	system("clear");  // 清屏

	printf("\n会员请刷卡！\n");
	scanf("%s",card_num);
	getchar();  // 清除换行符

	//  安
	char a = '\x1B';
	if(strncmp(card_num, &a, 1) == 0)
	{
		system("clear");  // 清屏
		manager_login();

		return;
	}
	//  安

	system("clear");

	FILE* fp = fopen(MEMBER_INFO_FILE, "rb");

	if(fp == NULL)
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
		return;
	}

	while(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		if(strcmp(mi.card_num, card_num) == 0)
			break;
	}

	if(feof(fp))
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
	}
	else
	{
		if(mi.delete_state == 1)
		{
			printf("\n此卡已注销，请联系工作人员处理！\n");
		}
		else
		{
			printf("\n尊贵的会员，您的个人信息如下：\n\n");
			print_member_info(&mi);


			char choice;
			// 如果是次卡，询问是否扣次
			if (mi.mt == cika)
			{
				printf("\n是否进行扣次操作？(Y/N): ");
				choice = getchar();
				getchar(); // 清除换行符

				if (choice == 'Y' || choice == 'y') 
				{
					member_deduct_times(card_num);
				}
			}

		}
	}



	fclose(fp);
	
	press_any_key();


}



void member_del(void)
{
	char num[50];
	member_info mi;

	printf("请输入要注销的会员的卡号/会员ID/手机号：");
	scanf("%s", num);
	getchar();

	FILE* fp = fopen(MEMBER_INFO_FILE, "r+");

	while(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		if(strcmp(num, mi.card_num) == 0 || strcmp(num, mi.phone) == 0 || atol(num) == mi.mid)
		{
			break;
		}
	}

	if(feof(fp))
	{
		printf("\n不存在此会员，注销失败！\n");
		printf("即将返回主菜单！\n");
                sleep(3);
	}
	else
	{
		char select;

		if(mi.delete_state == 1) 
		{
			printf("\n注销失败，此账号此前已注销！\n");
                        printf("即将返回主菜单！\n");
                        sleep(3);
			
			return;
		}

		printf("\n要注销的会员信息如下：\n");
		print_member_info(&mi);
		
		printf("\n是否确定要注销此会员(Y/N):");
		
		select = getchar();

		if(select == 'Y' || select == 'y')
		{
			mi.delete_state = 1;
			
			fseek(fp, -sizeof(mi), SEEK_CUR);

			fwrite(&mi, sizeof(mi), 1, fp);

			printf("\n注销成功！\n");
		}
		printf("即将返回主菜单！\n");
                sleep(3);
	}

	fclose(fp);
}


void member_modify (int operator2)
{
	char card_num[11];
	member_info mi;


	printf("请输入你的卡号：\n");
	scanf("%s", card_num);

	FILE* fp = fopen(MEMBER_INFO_FILE, "r+");

        while(fread(&mi, sizeof(mi), 1, fp) == 1)
        {
                if(strcmp(card_num, mi.card_num) == 0)
                {
                        break;
                }
        }

        if(feof(fp))
        {
                printf("\n不存在此会员，查询失败！\n");
		printf("即将返回主菜单！\n");
		sleep(3);

		return;
        }
	else if(mi.delete_state == 1)
	{
                
		printf("\n此账号此前已注销！\n");
		printf("即将返回主菜单！\n");
		sleep(3);

		return;

	}
        else
        {

                printf("\n要修改的会员信息如下：\n");
                print_member_info(&mi);

		printf("\n\n\n请按照如下提示修改会员信息。\n\n");
		if(operator2 == 1 || operator2 == 2)
		{

			printf("姓名：");
			scanf("%s", mi.name);
		}

		if(operator2 == 1 || operator2 == 3)
                {

			printf("性别（1-女,2-男）：");
			scanf("%d", (int*)&mi.s);
                }

		if(operator2 == 1 || operator2 == 4)
                {

			printf("手机号：");
			scanf("%s", mi.phone);
                }

		if(operator2 == 1 || operator2 == 5)
                {
			printf("会员类型（1-次卡,2-月卡,3-年卡）：");
			scanf("%d", (int*)&mi.mt);

			if(mi.mt == cika)
			{
				printf("剩余次数：");
				scanf("%d", &mi.remain_cnt);
			}

		}
		fseek(fp, -sizeof(mi), SEEK_CUR);
		fwrite(&mi, sizeof(mi), 1, fp);

	}

        fclose(fp);
	printf("\n修改成功！！\n");
        printf("即将返回主菜单！\n");
        sleep(3);
}


void member_query(void)
{
	char num[50];
        member_info mi;

        printf("请输入要查询的会员的卡号/会员ID/手机号：");
        scanf("%s", num);
        getchar();

        FILE* fp = fopen(MEMBER_INFO_FILE, "r+");

        while(fread(&mi, sizeof(mi), 1, fp) == 1)
        {
                if(strcmp(num, mi.card_num) == 0 || strcmp(num, mi.phone) == 0 || atol(num) == mi.mid)
                {
                        break;
                }
        }

        if(feof(fp))
        {
                printf("\n不存在此会员，查询失败！\n");
        }
        else
        {

                printf("\n要查询的会员信息如下：\n");
                print_member_info(&mi);
	}

        fclose(fp);
	
	press_any_key();
}



void print_member_info(const member_info* mi)
{
	printf("卡号：%s\n", mi->card_num);
	printf("会员ID：%u\n", mi->mid);
	printf("姓名：%s\n", mi->name);
	printf("性别：%s\n", mi->s == female ? "女" : "男");
	printf("手机号：%s\n", mi->phone);

	printf("会员类型：");
	if(mi->mt == cika)
	{
		printf("次卡\n剩余次数：%d\n", mi->remain_cnt);
	}
	else if(mi->mt == yueka)
	{
		printf("月卡\n");
	}
	else if(mi->mt == nianka)
	{
		printf("年卡\n");	
	}

	struct tm* dt;

	dt = localtime(&mi->expire_time);

	printf("到期时间：%d年%d月%d日 %02d:%02d\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday, dt->tm_hour, dt->tm_min);

	dt = localtime(&mi->reg_time);

	printf("注册时间：%d年%d月%d日 %02d:%02d\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday, dt->tm_hour, dt->tm_min);
}



void member_deduct_times(const char* card_num)
{
    member_info mi;
    int found = 0;

    // 以读写方式打开文件
    FILE* fp = fopen(MEMBER_INFO_FILE, "r+b");
    if (fp == NULL) {
        printf("无法打开会员数据文件！\n");
        return;
    }

    // 查找会员信息
    while (fread(&mi, sizeof(mi), 1, fp) == 1) {
        if (strcmp(mi.card_num, card_num) == 0 && mi.delete_state == 0) {
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("未找到有效的会员卡！\n");
        fclose(fp);
        return;
    }


    // 检查剩余次数
    if (mi.remain_cnt <= 0) {
        printf("剩余次数不足，无法使用！\n");
        fclose(fp);
        return;
    }

    // 检查有效期
    if (time(NULL) > mi.expire_time) {
        printf("会员卡已过期，无法使用！\n");
        fclose(fp);
        return;
    }

    // 执行扣次操作
    mi.remain_cnt--;

    // 回写文件
    fseek(fp, -sizeof(member_info), SEEK_CUR);
    if (fwrite(&mi, sizeof(member_info), 1, fp) == 1) {
        printf("扣次成功！剩余次数：%d\n", mi.remain_cnt);
    } else {
        printf("扣次失败，请重试！\n");
    }

    fclose(fp);
}
